<!--
 * @Author: jiangyg email@jiangyg.com
 * @Date: 2022-08-14 15:31:12
 * @LastEditors: jiangyg email@jiangyg.com
 * @LastEditTime: 2022-11-19 18:24:54
 * @FilePath: /frontend/mall-frontend/src/views/modules/admin/common/sku-select.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <el-select v-model="currentValue" filterable remote clearable @change="handleChangeEvent" placeholder="请输入SKU信息" :remote-method="remoteLoadSkuList" :loading="loading" style="width: 100%">
    <el-option v-for="item in dataList" :key="item.id" :label="item.name" :value="item.id">
      <el-row :gutter="20">
        <el-col :span="6">{{ item.id }}</el-col>
        <el-col :span="18">
          <span class="fr">{{ item.name }}</span>
        </el-col>
      </el-row>
    </el-option>
  </el-select>
</template>

<script lang="ts" setup>
import http from "@/utils/httpRequest";
import criteria from "@/utils/criteria";
import { ref, defineExpose, defineEmits, computed } from "vue";

// 属性定义
const props = defineProps({
  modelValue: {
    type: String,
    required: true,
  },
});

const pageSize = 20;

const dataList = ref([]);

const loading = ref(false);

const currentValue = computed({
  get() {
    return props.modelValue;
  },
  set(val) {
  }
});

// 父级组件的自定义事件
const emit = defineEmits(['update:modelValue']);

// 初始化
const init = (value) => {
  remoteLoadSkuList(value);
};

// 远程加载列表
const remoteLoadSkuList = (query) => {
  // 查询参数为空，清空下拉列表
  if (!query) {
    dataList.value = [];
    return;
  }
  // 查询参数不为空，则远程加载
  loading.value = true;
  http
    .post({
      url: `/product/sku/select`,
      data: {
        current: 1,
        size: pageSize,
        criterias: [criteria.ll("condition", query)],
      },
    }).then(({ data }) => {
      if (http.success(data)) {
        dataList.value = data.body.records;
        let total = data.body.total;
        if (total > pageSize) {
          dataList.value.push({ id: '', name: "请输入更精确的条件……" });
        }
      }
      loading.value = false;
    });
};

// 选中值事件
const handleChangeEvent = (val) => {
  emit("update:modelValue", val);
};

// 暴露方法
defineExpose({ init });
</script>
